<template>
  <div class="question-bank-container">
    <div class="page-header">
      <h1>题库管理</h1>
      <p>管理和预览各类面试题目（选择题与填空题）</p>
      
      <!-- 数据状态提示 -->
      <div v-if="isUsingMockData" class="data-status-alert">
        <el-alert 
          title="当前使用模拟数据" 
          type="warning" 
          :closable="false"
          show-icon
        >
          <template #default>
            <p><strong>问题原因：</strong>后端数据库中暂无题目数据，API返回"[图形推理题] 题目不足"错误。</p>
            <p><strong>解决方案：</strong></p>
            <ol>
              <li>确保后端Django服务已启动 (python manage.py runserver)</li>
              <li>导入题目数据：python manage.py import_questions LogistQuestions.xlsx</li>
              <li>或者：在后端管理面板中手动添加题目数据</li>
              <li>点击"重新加载"按钮刷新数据</li>
            </ol>
            <p><strong>当前状态：</strong>显示模拟数据用于界面功能测试，不影响前端功能验证。</p>
          </template>
        </el-alert>
      </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-bar">
      <div class="filter-tabs">
        <div class="filter-label">筛选类别：</div>
        <el-tag 
          v-for="stage in stageOptions" 
          :key="stage.value"
          :class="['filter-tag', { 'active': activeStage === stage.value }]"
          :type="activeStage === stage.value ? 'primary' : ''"
          @click="activeStage = stage.value"
          clickable
        >
          {{ stage.label }}
        </el-tag>
      </div>
      
      <div class="filter-skill">
        <el-select 
          v-model="selectedSkill" 
          placeholder="技能标签筛选" 
          clearable
          filterable
          allow-create
          @create="createSkillTag"
          style="width: 200px;"
        >
          <el-option 
            v-for="skill in allSkillTags" 
            :key="skill" 
            :label="skill" 
            :value="skill" 
          />
        </el-select>
      </div>
    </div>

    <!-- 操作栏 -->
    <div class="toolbar">
      
      <div class="action-section">
        <el-dropdown @command="handleAddQuestion">
          <el-button type="primary">
            <el-icon><Plus /></el-icon>
            新增题目
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="shortAnswer">简答题</el-dropdown-item>
              <el-dropdown-item command="fillBlank">填空题</el-dropdown-item>
              <el-dropdown-item command="multipleChoice">选择题</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <el-button @click="showAIGenerateDialog = true">
          <el-icon><Tools /></el-icon>
          AI生成建议题
        </el-button>
        
        <el-dropdown @command="handleImport">
          <el-button>
            <el-icon><Upload /></el-icon>
            导入题目
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="clipboard">
                <div class="import-item">
                  <span>从剪贴板导入</span>
                  <small>支持文本格式题目</small>
                </div>
              </el-dropdown-item>
              <el-dropdown-item command="csv">
                <div class="import-item">
                  <span>CSV文件导入</span>
                  <small>支持Excel/CSV格式</small>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <el-button @click="showImportHelp = true">
          <el-icon><QuestionFilled /></el-icon>
          导入帮助
        </el-button>
        
        <el-button @click="exportQuestions">
          <el-icon><Download /></el-icon>
          导出题库
        </el-button>
        
        <el-button @click="() => loadQuestions()" :loading="loading">
          <el-icon><Refresh /></el-icon>
          重新加载
        </el-button>
        

        
      </div>
    </div>
    
    <!-- 题目统计信息 -->
    <div class="stats-bar">
      <div class="stats-info">
        <span class="stats-count">{{ filteredQuestions?.length || 0 }}</span>
        <span class="stats-label">个题目</span>
        <span v-if="filteredQuestions?.length && questions?.length && filteredQuestions.length < questions.length" class="stats-total">
          / 共{{ questions?.length || 0 }}个
        </span>
        <span v-if="totalQuestions > questions?.length" class="stats-remote">
          / 数据库总共{{ totalQuestions }}个
        </span>
      </div>
      
      <!-- 分页控件 -->
      <div v-if="totalQuestions > currentPageSize" class="pagination-info">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="currentPageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="totalQuestions"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
          small
        />
      </div>
    </div>
    
    <!-- 题目列表 -->
    <div class="questions-grid">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="4" animated />
        <el-skeleton :rows="4" animated />
        <el-skeleton :rows="4" animated />
      </div>
      
      <!-- 简单测试显示 -->
      <div v-if="!loading && filteredQuestions.length === 0" class="no-questions">
        <el-empty description="没有找到题目">
          <el-button type="primary" @click="() => loadMockData()">加载测试数据</el-button>
        </el-empty>
      </div>
      
      <div 
        v-else-if="!loading"
        v-for="question in filteredQuestions" 
        :key="question.id"
        class="question-card"
      >
        <div class="card-header">
          <el-tag :type="getStageTagType(question.stage)">
            {{ getStageLabel(question.stage) }}
          </el-tag>
          <div class="card-actions">
            <el-button link @click="previewQuestion(question)">
              <el-icon><View /></el-icon>
            </el-button>
            <el-button link @click="editQuestion(question)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button link @click="deleteQuestion(question.id)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        
        <div class="card-content">
          <h3 class="question-title">{{ question.title }}</h3>
          <p class="question-content">{{ question.content }}</p>
          
          <!-- 题干图片 -->
          <div v-if="question.stem_image" class="question-image">
            <img :src="getImageUrl(question.stem_image)" alt="题目图片" @error="handleImageError" />
          </div>
          
          <!-- 选择题选项预览 -->
          <div v-if="question.type === 'multipleChoice' && question.options?.length > 0" class="options-preview">
            <div v-for="option in (question.options || []).slice(0, 2)" :key="option?.label" class="option-item">
              <span class="option-label">{{ option?.label }}:</span>
              <span class="option-content">{{ option?.content }}</span>
            </div>
            <div v-if="question.options?.length > 2" class="more-options">
              还有 {{ question.options.length - 2 }} 个选项...
            </div>
          </div>
          
          <div class="question-tags">
            <el-tag 
              v-for="tag in (question.type === 'shortAnswer' ? (question.topicTags ? question.topicTags.split(',').map(t => t.trim()) : []) : (question.skillTags || []))" 
              :key="tag"
              size="small"
              class="skill-tag"
            >
              {{ tag }}
            </el-tag>
            <el-tag size="small" type="success">
              {{ question?.score || 0 }}分
            </el-tag>
          </div>
          
          <div class="question-meta">
            <span class="meta-item">
              <el-icon><OfficeBuilding /></el-icon>
              适用岗位：{{ question.type === 'shortAnswer' ? (question.applicablePositions || []).join(', ') : (question.positions || []).join(', ') }}
            </span>
            <span class="meta-item">
              <el-icon><Clock /></el-icon>
              建议时长：{{ question?.timeLimit || 10 }}分钟
              <span v-if="question.answerDuration">({{ question.answerDuration }}秒)</span>
            </span>
            <span v-if="question.category" class="meta-item">
              <el-icon><Document /></el-icon>
              类别：{{ getCategoryLabel(question.category) }}
            </span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑题目弹窗 -->
    <el-dialog v-model="showQuestionDialog" :title="getDialogTitle()" width="800px">
      <el-form :model="questionForm" label-width="100px">
        <el-form-item label="题目标题">
          <el-input v-model="questionForm.title" placeholder="请输入题目标题" />
        </el-form-item>
        
        <el-form-item label="题目内容">
          <el-input 
            v-model="questionForm.content" 
            type="textarea" 
            :rows="4"
            placeholder="请输入题目内容"
          />
          <div v-if="questionForm.type === 'multipleChoice'" class="upload-hint">
            <el-button size="small" @click="uploadContentImage">上传图片</el-button>
            <span v-if="questionForm.contentImage" class="file-name">{{ questionForm.contentImage.name }}</span>
          </div>
        </el-form-item>
        
        <!-- 选择题选项 -->
        <template v-if="questionForm.type === 'multipleChoice'">
          <el-form-item v-for="(option, index) in questionForm.options" :key="index" :label="'选项' + (index + 1)">
            <div class="option-input">
              <el-input v-model="questionForm.options[index]" placeholder="请输入选项内容" />
              <el-button size="small" @click="uploadOptionImage(index)">上传图片</el-button>
              <span v-if="questionForm.optionImages[index]" class="file-name">{{ questionForm.optionImages[index].name }}</span>
            </div>
          </el-form-item>
          
          <el-form-item label="正确答案">
            <el-select v-model="questionForm.correctAnswer" placeholder="选择正确答案">
              <el-option v-for="(option, index) in questionForm.options" :key="index" :label="'选项' + (index + 1) + ': ' + option" :value="option" />
            </el-select>
          </el-form-item>
        </template>
        
        <!-- 填空题标准答案 -->
        <el-form-item v-if="questionForm.type === 'fillBlank'" label="标准答案">
          <el-input v-model="questionForm.standardAnswer" placeholder="请输入标准答案" />
        </el-form-item>

        <el-form-item v-if="questionForm.type === 'multipleChoice'" label="所属类别">
          <el-select v-model="questionForm.stage" placeholder="选择类别">
            <el-option label="逻辑思维类" value="logic" />
            <el-option label="创新思考类" value="innovation" />
            <el-option label="压力应对类" value="pressure" />
            <el-option label="专业技能类" value="professional" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="questionForm.type === 'fillBlank'" label="所属类别">
          <el-select v-model="questionForm.stage" placeholder="选择类别">
            <el-option label="逻辑思维类" value="logic" />
            <el-option label="创新思考类" value="innovation" />
            <el-option label="压力应对类" value="pressure" />
            <el-option label="专业技能类" value="professional" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="questionForm.type !== 'shortAnswer'" label="所属类别">
          <el-select v-model="questionForm.stage" placeholder="选择类别">
            <el-option label="逻辑思维类" value="logic" />
            <el-option label="创新思考类" value="innovation" />
            <el-option label="压力应对类" value="pressure" />
            <el-option label="专业技能类" value="professional" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="questionForm.type !== 'shortAnswer'" label="技能标签">
          <el-select 
            v-model="questionForm.skillTags" 
            multiple 
            placeholder="选择或输入技能标签"
            filterable
            allow-create
            @create="createSkillTag"
          >
            <el-option 
              v-for="skill in allSkillTags" 
              :key="skill" 
              :label="skill" 
              :value="skill" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="建议时长">
          <el-input-number 
            v-model="questionForm.timeLimit" 
            :min="1" 
            :max="60"
            controls-position="right"
          />
          <span class="unit">分钟</span>
        </el-form-item>
        
        <!-- 简答题特有字段 -->
        <template v-if="questionForm.type === 'shortAnswer'">
          <el-form-item label="题目类别">
            <el-select v-model="questionForm.category" placeholder="选择题目类别">
              <el-option label="创新思考类" value="innovation" />
              <el-option label="压力应对类" value="pressure" />
              <el-option label="专业技能类" value="professional" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="主题标签">
            <el-input 
              v-model="questionForm.topicTags" 
              placeholder="请输入主题标签，用逗号分隔"
            />
          </el-form-item>
          
          <el-form-item label="适用岗位">
            <el-select v-model="questionForm.applicablePositions" multiple placeholder="选择适用岗位">
              <el-option label="前端开发工程师" value="前端开发工程师" />
              <el-option label="后端开发工程师" value="后端开发工程师" />
              <el-option label="全栈开发工程师" value="全栈开发工程师" />
              <el-option label="产品经理" value="产品经理" />
              <el-option label="数据分析师" value="数据分析师" />
              <el-option label="UI设计师" value="UI设计师" />
              <el-option label="测试工程师" value="测试工程师" />
              <el-option label="运维工程师" value="运维工程师" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="回答时长">
            <el-input-number 
              v-model="questionForm.answerDuration" 
              :min="60" 
              :max="600"
              controls-position="right"
            />
            <span class="unit">秒</span>
          </el-form-item>
          
          <el-form-item label="评分标准">
            <el-input 
              v-model="questionForm.scoringCriteria" 
              type="textarea" 
              :rows="3"
              placeholder="请输入评分标准，如：1. 项目描述清晰度(30分)&#10;2. 技术深度(25分)&#10;3. 问题解决能力(25分)&#10;4. 团队协作(20分)"
            />
          </el-form-item>
          
          <el-form-item label="优秀回答示例">
            <el-input 
              v-model="questionForm.excellentAnswerExample" 
              type="textarea" 
              :rows="3"
              placeholder="请输入优秀回答示例"
            />
          </el-form-item>
        </template>
      </el-form>
      
      <template #footer>
        <el-button @click="showQuestionDialog = false">取消</el-button>
        <el-button type="primary" @click="saveQuestion">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 题目预览弹窗 -->
    <el-dialog v-model="showPreviewDialog" title="题目预览" width="700px">
      <div class="preview-content" v-if="previewingQuestion">
        <h3>{{ previewingQuestion.title }}</h3>
        <p>{{ previewingQuestion.content }}</p>
        
        <!-- 题干图片 -->
        <div v-if="previewingQuestion.stem_image" class="preview-image">
          <img :src="getImageUrl(previewingQuestion.stem_image)" alt="题目图片" @error="handleImageError" />
        </div>
        
        <!-- 选择题选项 -->
        <div v-if="previewingQuestion?.type === 'multipleChoice' && previewingQuestion?.options?.length > 0" class="preview-options">
          <h4>选项：</h4>
          <div v-for="option in (previewingQuestion.options || [])" :key="option?.label" class="preview-option-item">
            <span class="option-label">{{ option?.label }}:</span>
            <span class="option-content">{{ option?.content }}</span>
            <div v-if="option?.option_image" class="option-image">
              <img :src="getImageUrl(option.option_image)" alt="选项图片" @error="handleImageError" />
            </div>
          </div>
          <div class="correct-answer">
            <el-tag type="success">正确答案：{{ previewingQuestion?.answer }}</el-tag>
          </div>
        </div>
        
        <!-- 填空题答案 -->
        <div v-if="previewingQuestion.type === 'fillBlank'" class="preview-answer">
          <h4>标准答案：</h4>
          <p>{{ previewingQuestion.standardAnswer }}</p>
        </div>
        
        <!-- 简答题特有信息 -->
        <div v-if="previewingQuestion.type === 'shortAnswer'" class="preview-short-answer">
          <div v-if="previewingQuestion.topicTags" class="preview-section">
            <h4>主题标签：</h4>
            <p>{{ previewingQuestion.topicTags }}</p>
          </div>
          
          <div v-if="previewingQuestion.scoringCriteria" class="preview-section">
            <h4>评分标准：</h4>
            <div class="scoring-criteria" v-html="previewingQuestion.scoringCriteria.replace(/\n/g, '<br>')"></div>
          </div>
          
          <div v-if="previewingQuestion.excellentAnswerExample" class="preview-section">
            <h4>优秀回答示例：</h4>
            <p>{{ previewingQuestion.excellentAnswerExample }}</p>
          </div>
          
          <div v-if="previewingQuestion.applicablePositions && previewingQuestion.applicablePositions.length > 0" class="preview-section">
            <h4>适用岗位：</h4>
            <div class="positions-tags">
              <el-tag 
                v-for="position in previewingQuestion.applicablePositions" 
                :key="position"
                size="small"
                type="info"
              >
                {{ position }}
              </el-tag>
            </div>
          </div>
        </div>
        
        <div class="preview-meta">
          <el-tag :type="getStageTagType(previewingQuestion.stage)">
            {{ getStageLabel(previewingQuestion.stage) }}
          </el-tag>
          <el-tag type="success">{{ previewingQuestion.score }}分</el-tag>
          <span>建议时长：{{ previewingQuestion.timeLimit }}分钟</span>
          <span v-if="previewingQuestion.answerDuration">回答时长：{{ previewingQuestion.answerDuration }}秒</span>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showPreviewDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- AI生成建议题弹窗 -->
    <el-dialog v-model="showAIGenerateDialog" title="AI生成建议题" width="1000px">
      <div class="ai-generate-content">
        <div class="ai-header">
          <h3>选择面试项目</h3>
          <p>AI将根据面试的招聘信息生成相应的参考题目</p>
        </div>
        
        <!-- 面试列表 -->
        <div class="interview-list">
          <div class="interview-item" v-for="interview in mockInterviews" :key="interview.id">
            <div class="interview-info">
              <h4>{{ interview.title }}</h4>
              <p>{{ interview.position }} | {{ interview.company }}</p>
              <div class="interview-tags">
                <el-tag size="small" v-for="skill in interview.skills" :key="skill">{{ skill }}</el-tag>
              </div>
            </div>
            <div class="interview-actions">
              <el-button size="small" @click="generateQuestionsForInterview(interview)">生成题目</el-button>
            </div>
          </div>
        </div>
        
        <!-- 飞书集成 -->
        <div class="feishu-integration">
          <h3>飞书集成</h3>
          <div class="feishu-config">
            <el-button type="primary" @click="showFeishuDialog = true">
              <el-icon><Connection /></el-icon>
              从飞书导入项目
            </el-button>
            <p class="feishu-hint">配置公司API后，可从飞书读取相关文件，提供更有针对性的面试参考题目</p>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showAIGenerateDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 飞书导入弹窗 -->
    <el-dialog v-model="showFeishuDialog" title="飞书项目导入" width="600px">
      <div class="feishu-content">
        <el-form label-width="100px">
          <el-form-item label="App ID">
            <el-input placeholder="请输入飞书应用的App ID" />
          </el-form-item>
          
          <el-form-item label="App Secret">
            <el-input type="password" placeholder="请输入飞书应用的App Secret" />
          </el-form-item>
          
          <el-form-item label="Tenant Key">
            <el-input placeholder="请输入租户Key" />
          </el-form-item>
          
          <el-form-item label="项目文件夹">
            <el-input placeholder="请输入要导入的项目文件夹路径" />
          </el-form-item>
        </el-form>
        
        <div class="feishu-status">
          <el-alert 
            title="连接状态：未连接" 
            type="warning" 
            :closable="false"
            show-icon
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showFeishuDialog = false">取消</el-button>
        <el-button type="primary" @click="connectFeishu">连接飞书</el-button>
      </template>
    </el-dialog>

    <!-- 导入帮助对话框 -->
    <el-dialog v-model="showImportHelp" title="题目导入帮助" width="700px">
      <div class="import-help-content">
        <div class="help-section">
          <h3>📋 剪贴板导入</h3>
          <p>支持从剪贴板导入格式化的题目文本，格式如下：</p>
          <div class="help-example">
            <pre>1. 以下哪个是JavaScript的数据类型？
A. Number
B. Boolean
C. String
D. 以上都是
答案：D

2. 请填写JavaScript声明变量的关键字：___
答案：var或let或const</pre>
          </div>
          <p class="help-tip">💡 支持自动识别选择题和填空题，选择题需要包含A、B、C、D选项</p>
        </div>

        <div class="help-section">
          <h3>📊 CSV文件导入</h3>
          <p>支持导入CSV格式的题目数据，必须包含以下列：</p>
          <ul>
            <li><strong>题目内容</strong>：题目的主要内容</li>
            <li><strong>题目标题</strong>：题目的标题（可选）</li>
            <li><strong>题目类型</strong>：选择题/填空题/简答题（可选）</li>
            <li><strong>A、B、C、D</strong>：选择题的选项（可选）</li>
            <li><strong>答案</strong>：正确答案</li>
          </ul>
          <p class="help-tip">💡 可以下载示例CSV文件作为参考</p>
        </div>

        <div class="help-section">
          <h3>⚙️ 格式要求</h3>
          <ul>
            <li>CSV文件必须包含标题行</li>
            <li>支持UTF-8编码</li>
            <li>支持Excel导出的CSV格式</li>
            <li>导入的题目会自动添加"导入题目"标签</li>
          </ul>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="downloadCSVExample">下载CSV示例</el-button>
          <el-button type="primary" @click="showImportHelp = false">知道了</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Tools, Download, View, Edit, Delete, OfficeBuilding, Clock, ArrowDown, Upload, Connection, Refresh, QuestionFilled } from '@element-plus/icons-vue'
import { examApi, businessApi } from '@/services/api'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'QuestionBankView',
  components: {
    Plus,
    Tools,
    Download,
    View,
    Edit,
    Delete,
    OfficeBuilding,
    Clock,
    ArrowDown,
    Upload,
    Connection,
    Refresh,
    QuestionFilled
  },
  setup() {
    const router = useRouter()
    
    const activeStage = ref('all')
    const selectedSkill = ref('')
    
    // 筛选选项
    const stageOptions = [
      { value: 'all', label: '全部' },
      { value: 'logic', label: '逻辑思维类' },
      { value: 'innovation', label: '创新思考类' },
      { value: 'pressure', label: '压力应对类' },
      { value: 'professional', label: '专业技能类' }
    ]
    const showQuestionDialog = ref(false)
    const showPreviewDialog = ref(false)
    const showAIGenerateDialog = ref(false)
    const showFeishuDialog = ref(false)
    const showImportHelp = ref(false)
    const previewingQuestion = ref(null)
    const currentQuestionType = ref('shortAnswer')
    const loading = ref(false)
    const isUsingMockData = ref(false)
    
    // 分页相关
    const currentPage = ref(1)
    const currentPageSize = ref(20)
    const totalQuestions = ref(0)
    const allQuestionsCache = ref([]) // 缓存所有加载的题目
    
    // 技能标签 - 包含后端数据库中的TOPICS
    const allSkillTags = ref([
      // 后端数据库中的题目主题
      '逻辑思维题', '逻辑推理题', '类比推理题', '图形推理题', '数学运算', '阅读理解',
      // 其他技能标签
      '数据库', 'Python', 'Java', 'HTML', 'CSS', 'JavaScript', 'React', 'Vue', 'Node.js', '算法', '系统设计', '项目管理', '团队协作', '沟通能力'
    ])
    
    // 模拟面试数据
    const mockInterviews = ref([
      {
        id: 1,
        title: '前端开发工程师面试',
        position: '前端开发工程师',
        company: '科技公司A',
        skills: ['JavaScript', 'Vue.js', 'CSS', 'HTML']
      },
      {
        id: 2,
        title: '后端开发工程师面试',
        position: '后端开发工程师',
        company: '科技公司B',
        skills: ['Java', 'Spring', '数据库', 'Redis']
      },
      {
        id: 3,
        title: '产品经理面试',
        position: '产品经理',
        company: '互联网公司C',
        skills: ['产品设计', '用户体验', '数据分析', '项目管理']
      }
    ])
    
    const questionForm = reactive({
      id: null,
      type: 'shortAnswer', // shortAnswer, fillBlank, multipleChoice
      title: '',
      content: '',
      stage: '',
      skillTags: [],
      positions: [],
      timeLimit: 10,
      // 简答题特有字段
      evaluationPoints: '',
      excellentAnswer: '',
      // 填空题特有字段
      standardAnswer: '',
      // 选择题特有字段
      options: ['', '', '', ''],
      correctAnswer: '',
      optionImages: [null, null, null, null],
      contentImage: null,
      // 视频题新增字段
      topicTags: '',
      excellentAnswerExample: '',
      scoringCriteria: '',
      answerDuration: 180,
      category: 'professional',
      applicablePositions: []
    })
    
    // 题目数据
    const questions = ref([])
    
    // 将后端exams数据转换为前端格式（逻辑题）
    const convertExamsQuestion = (backendQuestion) => {
      if (!backendQuestion) return null
      
      const converted = {
        id: backendQuestion.id || Date.now(),
        type: backendQuestion.question_type === 1 ? 'multipleChoice' : 'fillBlank',
        title: backendQuestion.title || `Q${String(backendQuestion.id || Date.now()).padStart(3, '0')}`,
        content: backendQuestion.stem || '',
        stage: 'logic', // 所有exams题目都属于逻辑思维类
        skillTags: backendQuestion.topic ? [backendQuestion.topic] : ['未分类'],
        positions: backendQuestion.positions ? backendQuestion.positions.split(',') : ['通用'],
        timeLimit: backendQuestion.suggested_time || 10,
        stem_image: backendQuestion.stem_image || null,
        score: backendQuestion.score || 1,
        answer: backendQuestion.answer || '',
        options: Array.isArray(backendQuestion.options) ? backendQuestion.options : [],
        correctAnswer: backendQuestion.answer || '',
        standardAnswer: backendQuestion.answer || '',
        evaluationPoints: backendQuestion.evaluation_points || '',
        excellentAnswer: backendQuestion.excellent_answer || '',
        source: 'exams' // 标记数据来源
      }
      
      return converted
    }
    
    // 将后端spark数据转换为前端格式（视频题/简答题）
    const convertSparkQuestion = (backendQuestion) => {
      if (!backendQuestion) return null
      
      return {
        id: backendQuestion.id || Date.now(),
        type: 'shortAnswer', // spark的VideoQuestion都是简答题
        title: backendQuestion.title || `V${String(backendQuestion.id || Date.now()).padStart(3, '0')}`,
        content: backendQuestion.content || '',
        stage: backendQuestion.category || 'professional', // 使用新的category字段
        timeLimit: Math.floor((backendQuestion.answer_duration || 180) / 60), // 转换为分钟
        score: 5, // 视频题默认5分
        answer: '',
        options: [],
        correctAnswer: '',
        standardAnswer: '',
        // 视频题特有字段
        topicTags: backendQuestion.topic_tags || '',
        excellentAnswerExample: backendQuestion.excellent_answer_example || '',
        scoringCriteria: backendQuestion.scoring_criteria || '',
        answerDuration: backendQuestion.answer_duration || 180,
        category: backendQuestion.category || 'professional',
        applicablePositions: backendQuestion.applicable_positions || [],
        created_by_name: backendQuestion.created_by_name || '',
        created_at: backendQuestion.created_at || '',
        source: 'spark' // 标记数据来源
      }
    }
    
    // 加载逻辑题（从exams API）
    const loadLogistQuestions = async (page = 1, pageSize = 20) => {
      try {
        const response = await businessApi.getLogistQuestions(page, pageSize)
        console.log('Exams API响应:', response)
        
        // 处理分页格式的响应 {results: [...], count: 61}
        if (response && response.results && Array.isArray(response.results)) {
          const questions = response.results.map(convertExamsQuestion).filter(q => q !== null)
          
          // 更新总数
          if (response.count) {
            totalQuestions.value = Math.max(totalQuestions.value, response.count)
          }
          
          // 如果还有更多数据，提醒用户
          if (response.next && page === 1) {
            console.warn(`还有更多数据未加载，当前加载了${questions.length}个，总共${response.count}个`)
            ElMessage.info(`已加载${questions.length}个逻辑题，总共${response.count}个，可使用分页查看更多`)
          }
          
          return { questions, total: response.count || 0, hasNext: !!response.next }
        } else if (response && response.data && Array.isArray(response.data)) {
          const questions = response.data.map(convertExamsQuestion).filter(q => q !== null)
          return { questions, total: questions.length, hasNext: false }
        } else if (response && Array.isArray(response)) {
          const questions = response.map(convertExamsQuestion).filter(q => q !== null)
          return { questions, total: questions.length, hasNext: false }
        }
        return { questions: [], total: 0, hasNext: false }
      } catch (error) {
        console.error('加载逻辑题失败:', error)
        return { questions: [], total: 0, hasNext: false }
      }
    }
    
    // 加载视频题（从spark API）
    const loadVideoQuestions = async (page = 1, pageSize = 20) => {
      try {
        const response = await businessApi.getVideoQuestions(page, pageSize)
        console.log('Spark API响应:', response)
        
        // 处理分页格式的响应 {results: [...], count: 0}
        if (response && response.results && Array.isArray(response.results)) {
          const questions = response.results.map(convertSparkQuestion).filter(q => q !== null)
          
          // 更新总数
          if (response.count) {
            totalQuestions.value = Math.max(totalQuestions.value, response.count)
          }
          
          return { questions, total: response.count || 0, hasNext: !!response.next }
        } else if (response && response.data && Array.isArray(response.data)) {
          const questions = response.data.map(convertSparkQuestion).filter(q => q !== null)
          return { questions, total: questions.length, hasNext: false }
        } else if (response && Array.isArray(response)) {
          const questions = response.map(convertSparkQuestion).filter(q => q !== null)
          return { questions, total: questions.length, hasNext: false }
        }
        return { questions: [], total: 0, hasNext: false }
      } catch (error) {
        console.error('加载视频题失败:', error)
        return { questions: [], total: 0, hasNext: false }
      }
    }
    
    // 加载指定页面的题目
    const loadQuestions = async (page = null, pageSize = null) => {
      try {
        loading.value = true
        
        const targetPage = page || currentPage.value
        const targetPageSize = pageSize || currentPageSize.value
        
        console.log(`加载第${targetPage}页，每页${targetPageSize}个题目`)
        
        // 并行加载两种类型的题目
        const [logistResult, videoResult] = await Promise.all([
          loadLogistQuestions(targetPage, targetPageSize),
          loadVideoQuestions(targetPage, targetPageSize)
        ])
        
        // 合并题目
        const allQuestions = [...logistResult.questions, ...videoResult.questions]
        const totalCount = logistResult.total + videoResult.total
        
        if (allQuestions.length > 0) {
          questions.value = allQuestions
          totalQuestions.value = totalCount
            isUsingMockData.value = false
          
          // 统计所有技能标签
          const allSkillTagsInData = new Set()
          const questionsWithImages = []
          
          allQuestions.forEach(q => {
            if (q.skillTags && Array.isArray(q.skillTags)) {
              q.skillTags.forEach(tag => allSkillTagsInData.add(tag))
            }
            if (q.stem_image) {
              questionsWithImages.push({
                title: q.title,
                skillTags: q.skillTags,
                stem_image: q.stem_image
              })
            }
          })
          

          
          // 动态更新技能标签列表
          const newSkillTags = Array.from(allSkillTagsInData)
          newSkillTags.forEach(tag => {
            if (!allSkillTags.value.includes(tag)) {
              allSkillTags.value.push(tag)
            }
          })
          

          
          // 缓存当前页数据
          const cacheKey = `${targetPage}-${targetPageSize}`
          allQuestionsCache.value[cacheKey] = allQuestions
          
          ElMessage.success(`成功加载第${targetPage}页，共 ${allQuestions.length} 个题目（逻辑题：${logistResult.questions.length}，视频题：${videoResult.questions.length}）`)
          
          // 如果有更多数据，提示用户
          if (totalCount > allQuestions.length) {
            ElMessage.info(`数据库总共有${totalCount}个题目，当前显示第${targetPage}页`)
          }
        } else {
          ElMessage.warning('当前页面暂无题目数据，显示模拟数据')
          loadMockData()
        }
      } catch (error) {
        console.error('加载题目失败:', error)
        ElMessage.error('加载题目失败，显示模拟数据')
        loadMockData()
      } finally {
        loading.value = false
      }
    }
    
    // 加载模拟数据用于测试
    const loadMockData = () => {
      isUsingMockData.value = true
      questions.value = [
        {
          id: 1,
          type: 'multipleChoice',
          title: 'Q001',
          content: '1+1=？',
          stage: 'logic',
          skillTags: ['逻辑推理题'],
          positions: ['全栈开发', '后端开发'],
          timeLimit: 10,
          stem_image: null,
          score: 2,
          answer: 'B',
          options: [
            { label: 'A', content: '1', option_image: null },
            { label: 'B', content: '2', option_image: null },
            { label: 'C', content: '3', option_image: null },
            { label: 'D', content: '4', option_image: null }
          ],
          correctAnswer: 'B',
          source: 'mock'
        },
        {
          id: 2,
          type: 'fillBlank',
          title: 'Q002',
          content: '请填写下列空白：2+2=___',
          stage: 'logic',
          skillTags: ['逻辑思维题'],
          positions: ['全栈开发', '后端开发'],
          timeLimit: 5,
          stem_image: null,
          score: 2,
          answer: '4',
          options: [],
          standardAnswer: '4',
          source: 'mock'
        },
        {
          id: 3,
          type: 'shortAnswer',
          title: 'V001',
          content: '请描述一下您在团队协作中遇到的挑战以及如何解决的？',
          stage: 'professional',
          skillTags: ['团队协作', '沟通能力'],
          positions: ['产品经理', '项目经理'],
          timeLimit: 15,
          score: 5,
          evaluationPoints: '1. 具体的挑战描述 2. 解决方案的可行性 3. 团队协作技巧',
          excellentAnswer: '优秀回答应包含具体案例、解决思路和反思总结',
          source: 'mock'
        }
      ]
    }
    
    const filteredQuestions = computed(() => {
      if (!questions.value || !Array.isArray(questions.value) || questions.value.length === 0) {
        return []
      }
      
      let filtered = [...questions.value]
      
      if (activeStage.value !== 'all') {
        filtered = filtered.filter(q => q.stage === activeStage.value)
      }
      
      if (selectedSkill.value) {
        filtered = filtered.filter(q => 
          q.skillTags && Array.isArray(q.skillTags) && 
          q.skillTags.some(tag => tag.toLowerCase().includes(selectedSkill.value.toLowerCase()))
        )
      }
      
      return filtered
    })
    
    // 新增：当筛选条件改变时，重新从数据库加载匹配的题目
    const loadFilteredQuestions = async () => {
      if (!selectedSkill.value && activeStage.value === 'all') {
        // 没有筛选条件，加载默认数据
        await loadQuestions()
        return
      }
      
      try {
        loading.value = true
        
        // 由于后端有分页限制，需要多次调用获取所有数据
        let allLogistQuestions = []
        let allVideoQuestions = []
        
        // 获取所有逻辑题
        let currentPage = 1
        let hasMoreLogist = true
        
        while (hasMoreLogist && currentPage <= 10) { // 最多10页，避免无限循环
          const logistResult = await loadLogistQuestions(currentPage, 20)
          allLogistQuestions = allLogistQuestions.concat(logistResult.questions)
          
          hasMoreLogist = logistResult.hasNext
          currentPage++
        }
        
        // 获取所有视频题
        currentPage = 1
        let hasMoreVideo = true
        
        while (hasMoreVideo && currentPage <= 10) {
          const videoResult = await loadVideoQuestions(currentPage, 20)
          allVideoQuestions = allVideoQuestions.concat(videoResult.questions)
          
          hasMoreVideo = videoResult.hasNext
          currentPage++
        }
        
        let allQuestions = [...allLogistQuestions, ...allVideoQuestions]
        
        // 应用筛选条件
        if (activeStage.value !== 'all') {
          allQuestions = allQuestions.filter(q => q.stage === activeStage.value)
        }
        
        if (selectedSkill.value) {
          allQuestions = allQuestions.filter(q => 
            q.skillTags && Array.isArray(q.skillTags) && 
            q.skillTags.some(tag => tag.toLowerCase().includes(selectedSkill.value.toLowerCase()))
          )
        }
        
        questions.value = allQuestions
        totalQuestions.value = allQuestions.length
        isUsingMockData.value = false
        
        if (allQuestions.length === 0) {
          ElMessage.warning(`没有找到包含"${selectedSkill.value}"标签的题目`)
        } else {
          const imageCount = allQuestions.filter(q => q.stem_image).length
          ElMessage.success(`找到 ${allQuestions.length} 个包含"${selectedSkill.value}"标签的题目，其中 ${imageCount} 个有图片`)
        }
        
      } catch (error) {
        console.error('加载筛选题目失败:', error)
        ElMessage.error('加载筛选题目失败')
      } finally {
        loading.value = false
      }
    }
    
    // 监听筛选条件变化
    watch([selectedSkill, activeStage], () => {
      if (selectedSkill.value || activeStage.value !== 'all') {
        loadFilteredQuestions()
      } else {
        loadQuestions()
      }
    })
    
    const getStageTagType = (stage) => {
      const typeMap = {
        logic: 'primary',
        innovation: 'success',
        pressure: 'warning',
        professional: 'info'
      }
      return typeMap[stage] || 'default'
    }
    
    const getStageLabel = (stage) => {
      const labelMap = {
        logic: '逻辑思维类',
        innovation: '创新思考类',
        pressure: '压力应对类',
        professional: '专业技能类'
      }
      return labelMap[stage] || '未知'
    }
    
    const getCategoryLabel = (category) => {
      const labelMap = {
        innovation: '创新思考类',
        pressure: '压力应对类',
        professional: '专业技能类'
      }
      return labelMap[category] || '未知'
    }
    
    const createSkillTag = (tag) => {
      if (tag && !allSkillTags.value.includes(tag)) {
        allSkillTags.value.push(tag)
      }
    }
    
    // 处理图片URL
    const getImageUrl = (imagePath) => {
      if (!imagePath) return ''
      
      // 如果已经是完整URL，直接返回
      if (imagePath.startsWith('http')) {
        return imagePath
      }
      
      // 如果是相对路径，添加后端域名
      if (imagePath.startsWith('/')) {
        return `http://127.0.0.1:8000${imagePath}`
      }
      
      // 其他情况，添加完整路径
      return `http://127.0.0.1:8000/media/${imagePath}`
    }
    
    // 处理图片加载错误
    const handleImageError = (event) => {
      console.warn('图片加载失败:', event.target.src)
      event.target.style.display = 'none'
      // 可以设置一个默认图片
      // event.target.src = '/path/to/default-image.png'
    }
    
    const handleAddQuestion = (type) => {
      currentQuestionType.value = type
      // 重置表单
      Object.assign(questionForm, {
        id: null,
        type: type,
        title: '',
        content: '',
        stage: type === 'shortAnswer' ? 'professional' : 'logic',
        skillTags: [],
        positions: [],
        timeLimit: type === 'shortAnswer' ? 15 : 10,
        evaluationPoints: '',
        excellentAnswer: '',
        standardAnswer: '',
        options: ['', '', '', ''],
        correctAnswer: '',
        optionImages: [null, null, null, null],
        contentImage: null
      })
      showQuestionDialog.value = true
    }
    
    const handleImport = (type) => {
      if (type === 'clipboard') {
        importFromClipboard()
      } else if (type === 'csv') {
        importFromCSV()
      }
    }

    // 从剪贴板导入题目
    const importFromClipboard = async () => {
      try {
        const text = await navigator.clipboard.readText()
        if (!text.trim()) {
          ElMessage.warning('剪贴板内容为空')
          return
        }

        const parsedQuestions = parseClipboardText(text)
        if (parsedQuestions.length === 0) {
          ElMessage.warning('未能解析出有效的题目数据')
          return
        }

        await saveImportedQuestions(parsedQuestions)
        ElMessage.success(`成功从剪贴板导入 ${parsedQuestions.length} 个题目`)
      } catch (error) {
        ElMessage.error('读取剪贴板失败，请检查浏览器权限')
      }
    }

    // 解析剪贴板文本
    const parseClipboardText = (text) => {
      const questions = []
      const lines = text.split('\n').filter(line => line.trim())
      
      let currentQuestion = null
      let questionCounter = 1

      for (let line of lines) {
        line = line.trim()
        
        if (/^(\d+\.|Q\d+|题目\d+)/.test(line) || line.includes('？') || line.includes('?')) {
          if (currentQuestion) {
            questions.push(currentQuestion)
          }
          
          currentQuestion = {
            title: `Q${String(questionCounter).padStart(3, '0')}`,
            content: line.replace(/^(\d+\.|Q\d+|题目\d+)[：:]?\s*/, ''),
            type: 'multipleChoice',
            stage: 'logic',
            skillTags: ['导入题目'],
            positions: ['通用'],
            timeLimit: 10,
            score: 2,
            options: [],
            correctAnswer: '',
            standardAnswer: ''
          }
          questionCounter++
        } 
        else if (currentQuestion && /^[A-Z]\.|^[A-Z][:：]/.test(line)) {
          const match = line.match(/^([A-Z])[\.:：]\s*(.+)/)
          if (match) {
            currentQuestion.options.push({
              label: match[1],
              content: match[2],
              option_image: null
            })
          }
        }
        else if (currentQuestion && /^(答案|正确答案|答)[：:]/.test(line)) {
          const answer = line.replace(/^(答案|正确答案|答)[：:]\s*/, '')
          currentQuestion.correctAnswer = answer
          currentQuestion.answer = answer
        }
      }

      if (currentQuestion) {
        questions.push(currentQuestion)
      }

      questions.forEach(q => {
        if (q.options.length === 0) {
          q.type = 'fillBlank'
          q.standardAnswer = q.correctAnswer || ''
        }
      })

      return questions
    }

        // 从CSV文件导入
    const importFromCSV = () => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.csv,.xlsx,.xls'
      input.onchange = (e) => {
        const file = e.target.files[0]
        if (file) {
          const reader = new FileReader()
          reader.onload = async (event) => {
            try {
              const csvText = event.target.result
              const parsedQuestions = parseCSVText(csvText)
              
              if (parsedQuestions.length === 0) {
                ElMessage.warning('CSV文件中没有找到有效的题目数据')
                return
              }

              await saveImportedQuestions(parsedQuestions)
              ElMessage.success(`成功从CSV文件导入 ${parsedQuestions.length} 个题目`)
            } catch (error) {
              ElMessage.error('CSV文件解析失败：' + error.message)
            }
          }
          reader.readAsText(file, 'UTF-8')
        }
      }
      input.click()
    }

    // 解析CSV文本
    const parseCSVText = (csvText) => {
      const questions = []
      const lines = csvText.split('\n').filter(line => line.trim())
      
      if (lines.length < 2) {
        throw new Error('CSV文件格式错误，至少需要标题行和数据行')
      }

      const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''))
      
      const titleIndex = headers.findIndex(h => h.includes('题目') || h.includes('标题') || h.toLowerCase().includes('title'))
      const contentIndex = headers.findIndex(h => h.includes('内容') || h.includes('题干') || h.toLowerCase().includes('content'))
      const typeIndex = headers.findIndex(h => h.includes('类型') || h.toLowerCase().includes('type'))
      const answserIndex = headers.findIndex(h => h.includes('答案') || h.toLowerCase().includes('answer'))

      if (contentIndex === -1) {
        throw new Error('未找到题目内容列，请确保CSV包含"题目内容"或"content"列')
      }

      for (let i = 1; i < lines.length; i++) {
        const row = lines[i].split(',').map(cell => cell.trim().replace(/"/g, ''))
        
        if (row.length < headers.length) continue

        const question = {
          title: titleIndex >= 0 ? row[titleIndex] : `Q${String(i).padStart(3, '0')}`,
          content: contentIndex >= 0 ? row[contentIndex] : '',
          type: 'multipleChoice',
          stage: 'logic',
          skillTags: ['CSV导入'],
          positions: ['通用'],
          timeLimit: 10,
          score: 2,
          options: [],
          correctAnswer: answserIndex >= 0 ? row[answserIndex] : '',
          standardAnswer: answserIndex >= 0 ? row[answserIndex] : ''
        }

        if (typeIndex >= 0) {
          const type = row[typeIndex].toLowerCase()
          if (type.includes('填空') || type.includes('fill')) {
            question.type = 'fillBlank'
          } else if (type.includes('简答') || type.includes('short')) {
            question.type = 'shortAnswer'
            question.stage = 'professional'
          }
        }

        for (let j = 0; j < headers.length; j++) {
          const header = headers[j].toLowerCase()
          if (/^[a-d]$/.test(header) || header.includes('选项')) {
            if (row[j] && row[j].trim()) {
              question.options.push({
                label: header.toUpperCase(),
                content: row[j],
                option_image: null
              })
            }
          }
        }

        if (question.content) {
          questions.push(question)
        }
      }

      return questions
    }
    
    const editQuestion = (question) => {
      // 重置表单
      Object.assign(questionForm, {
        id: null,
        type: 'shortAnswer',
        title: '',
        content: '',
        stage: '',
        skillTags: [],
        positions: [],
        timeLimit: 10,
        evaluationPoints: '',
        excellentAnswer: '',
        standardAnswer: '',
        options: ['', '', '', ''],
        correctAnswer: '',
        optionImages: [null, null, null, null],
        contentImage: null,
        topicTags: '',
        excellentAnswerExample: '',
        scoringCriteria: '',
        answerDuration: 180,
        category: 'professional',
        applicablePositions: []
      })
      
      // 填充数据
      Object.assign(questionForm, { ...question })
      showQuestionDialog.value = true
    }
    
    const deleteQuestion = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个题目吗？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 找到题目确定来源
        const question = questions.value.find(q => q.id === id)
        if (!question) {
          ElMessage.error('题目不存在')
          return
        }
        
        // 根据来源调用不同的删除API
        if (question.source === 'exams') {
          await businessApi.deleteLogistQuestion(id)
        } else if (question.source === 'spark') {
          await businessApi.deleteVideoQuestion(id)
        }
        
        // 从前端列表删除
        const index = questions.value.findIndex(q => q.id === id)
        if (index > -1) {
          questions.value.splice(index, 1)
        }
        
        ElMessage.success('题目删除成功')
        
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除题目失败：' + (error.response?.data?.message || error.message))
        }
      }
    }
    
    const previewQuestion = (question) => {
      previewingQuestion.value = question
      showPreviewDialog.value = true
    }
    
    const saveQuestion = async () => {
      try {
        if (questionForm.id) {
          // 编辑现有题目
          const question = questions.value.find(q => q.id === questionForm.id)
          if (question && question.source === 'exams') {
            const backendQuestion = convertToExamsFormat(questionForm)
            await businessApi.updateLogistQuestion(questionForm.id, backendQuestion)
          } else if (question && question.source === 'spark') {
            const backendQuestion = convertToSparkFormat(questionForm)
            await businessApi.updateVideoQuestion(questionForm.id, backendQuestion)
          }
          
          const index = questions.value.findIndex(q => q.id === questionForm.id)
          if (index > -1) {
            questions.value[index] = { ...questionForm }
          }
          
          ElMessage.success('题目更新成功')
        } else {
          // 添加新题目
          let response
          if (questionForm.type === 'shortAnswer') {
            // 简答题保存到spark
            const backendQuestion = convertToSparkFormat(questionForm)
            console.log('准备保存视频简答题:', backendQuestion)
            response = await businessApi.createVideoQuestion(backendQuestion)
            console.log('视频简答题保存响应:', response)
          } else {
            // 选择题和填空题保存到exams
            const backendQuestion = convertToExamsFormat(questionForm)
            response = await businessApi.createLogistQuestion(backendQuestion)
          }
          
          questions.value.push({
            ...questionForm,
            id: response.data?.id || response.id || Date.now(),
            source: questionForm.type === 'shortAnswer' ? 'spark' : 'exams'
          })
          
          ElMessage.success('题目创建成功')
        }
        
        showQuestionDialog.value = false
        
        // 重新加载题目列表
        setTimeout(() => {
          loadQuestions()
        }, 1000)
        
      } catch (error) {
        console.error('保存题目详细错误:', error)
        console.error('错误响应:', error.response)
        console.error('错误状态:', error.response?.status)
        console.error('错误数据:', error.response?.data)
        
        let errorMessage = '保存题目失败'
        if (error.response?.status === 404) {
          errorMessage = 'API端点不存在，请检查后端服务'
        } else if (error.response?.status === 401) {
          errorMessage = '认证失败，请重新登录'
        } else if (error.response?.status === 400) {
          errorMessage = '数据格式错误：' + (error.response?.data?.message || error.response?.data?.detail || '请检查输入数据')
        } else if (error.response?.data?.message) {
          errorMessage = error.response.data.message
        } else if (error.message) {
          errorMessage = error.message
        }
        
        ElMessage.error(errorMessage)
      }
    }
    
    const getDialogTitle = () => {
      const typeMap = {
        shortAnswer: '新增简答题',
        fillBlank: '新增填空题',
        multipleChoice: '新增选择题'
      }
      return questionForm.id ? '编辑题目' : (typeMap[questionForm.type] || '新增题目')
    }
    
    const uploadContentImage = () => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'
      input.onchange = (e) => {
        const file = e.target.files[0]
        if (file) {
          questionForm.contentImage = file
        }
      }
      input.click()
    }
    
    const uploadOptionImage = (index) => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'
      input.onchange = (e) => {
        const file = e.target.files[0]
        if (file) {
          questionForm.optionImages[index] = file
        }
      }
      input.click()
    }
    
    const generateQuestions = () => {
      showAIGenerateDialog.value = true
    }
    
    const generateQuestionsForInterview = (interview) => {
      const generatedQuestions = [
        {
          title: `${interview.position}技能评估`,
          content: `针对${interview.position}岗位的专业技能评估题目`,
          type: 'shortAnswer',
          stage: 'professional',
          skillTags: interview.skills.slice(0, 2),
          timeLimit: 15
        }
      ]
      
      const action = confirm('题目生成完成，选择操作：\n确定：加入题库\n取消：下载CSV')
      if (action) {
        generatedQuestions.forEach(q => {
          questions.value.push({
            ...q,
            id: Date.now() + Math.random()
          })
        })
        showAIGenerateDialog.value = false
      } else {
        exportQuestionsAsCSV(generatedQuestions)
      }
    }
    
    const exportQuestionsAsCSV = (questionsToExport) => {
      // 实现CSV导出逻辑
    }
    
    const connectFeishu = () => {
      // 实现飞书连接逻辑
      showFeishuDialog.value = false
    }
    
    const exportQuestions = () => {
      const dataStr = JSON.stringify(questions.value, null, 2)
      const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr)
      
      const exportFileDefaultName = 'questions.json'
      
      const linkElement = document.createElement('a')
      linkElement.setAttribute('href', dataUri)
      linkElement.setAttribute('download', exportFileDefaultName)
      linkElement.click()
    }

    // 下载CSV示例文件
    const downloadCSVExample = () => {
      const csvContent = `题目标题,题目内容,题目类型,A,B,C,D,答案
Q001,以下哪个是JavaScript的数据类型？,选择题,Number,Boolean,String,以上都是,D
Q002,请填写JavaScript声明变量的关键字：___,填空题,,,,, var或let或const
Q003,什么是闭包？,简答题,,,,,闭包是指有权访问另一个函数作用域中变量的函数
Q004,1+1等于多少？,选择题,1,2,3,4,B
Q005,CSS的全称是什么？,填空题,,,,,Cascading Style Sheets`
      
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob)
        link.setAttribute('href', url)
        link.setAttribute('download', '题目导入示例.csv')
        link.style.visibility = 'hidden'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
      }
      
      ElMessage.success('CSV示例文件已下载')
    }

    // 保存导入的题目到后端数据库
    const saveImportedQuestions = async (questionsToSave) => {
      let savedCount = 0
      let failedCount = 0
      
      for (const question of questionsToSave) {
        try {
          if (question.type === 'shortAnswer') {
            // 简答题保存到spark
            const backendQuestion = convertToSparkFormat(question)
            await businessApi.createVideoQuestion(backendQuestion)
          } else {
            // 选择题和填空题保存到exams
            const backendQuestion = convertToExamsFormat(question)
            await businessApi.createLogistQuestion(backendQuestion)
          }
          
          savedCount++
        } catch (error) {
          failedCount++
          console.error('保存题目失败:', error)
        }
      }
      
      if (savedCount > 0) {
        ElMessage.success(`成功保存 ${savedCount} 个题目到数据库`)
        await loadQuestions()
      }
      
      if (failedCount > 0) {
        ElMessage.warning(`有 ${failedCount} 个题目保存失败`)
      }
    }

    // 将前端格式转换为exams后端格式
    const convertToExamsFormat = (frontendQuestion) => {
      const topicMapping = {
        '导入题目': '逻辑思维题',
        'CSV导入': '逻辑思维题',
        '逻辑思维题': '逻辑思维题',
        '逻辑推理题': '逻辑推理题',
        '类比推理题': '类比推理题',
        '图形推理题': '图形推理题', 
        '数学运算': '数学运算',
        '阅读理解': '阅读理解'
      }
      
      let topic = '逻辑思维题'
      if (frontendQuestion.skillTags && frontendQuestion.skillTags.length > 0) {
        const firstTag = frontendQuestion.skillTags[0]
        topic = topicMapping[firstTag] || '逻辑思维题'
      }
      
      const backendQuestion = {
        question_id: frontendQuestion.title || `Q${Date.now()}`,
        stem: frontendQuestion.content || '',
        question_type: frontendQuestion.type === 'multipleChoice' ? 1 : 2,
        topic: topic,
        score: parseInt(frontendQuestion.score) || 2,
        answer: frontendQuestion.type === 'multipleChoice' ? frontendQuestion.correctAnswer : frontendQuestion.standardAnswer,
        suggested_time: parseInt(frontendQuestion.timeLimit) || 10,
        title: frontendQuestion.title || '',
        skill_tags: frontendQuestion.skillTags ? frontendQuestion.skillTags.join(',') : '',
        positions: frontendQuestion.positions ? frontendQuestion.positions.join(',') : ''
      }
      
      if (frontendQuestion.type === 'multipleChoice' && frontendQuestion.options?.length > 0) {
        backendQuestion.options = frontendQuestion.options.map(opt => ({
          label: opt.label || 'A',
          content: opt.content || '',
          option_image: opt.option_image || null
        }))
      }
      
      return backendQuestion
    }

    // 将前端格式转换为spark后端格式
    const convertToSparkFormat = (frontendQuestion) => {
      return {
        title: frontendQuestion.title || '',
        content: frontendQuestion.content || '',
        topic_tags: frontendQuestion.topicTags || '',
        excellent_answer_example: frontendQuestion.excellentAnswerExample || '',
        scoring_criteria: frontendQuestion.scoringCriteria || '',
        answer_duration: frontendQuestion.answerDuration || 180,
        category: frontendQuestion.category || 'professional',
        applicable_positions: frontendQuestion.applicablePositions || []
      }
    }
    
    // 加载所有题目
    const loadAllQuestions = async () => {
      await loadQuestions()
    }
    
    // 处理页面大小变化
    const handlePageSizeChange = (newPageSize) => {
      currentPageSize.value = newPageSize
      currentPage.value = 1 // 重置到第一页
      loadQuestions(1, newPageSize)
    }
    
    // 处理当前页变化
    const handleCurrentPageChange = (newPage) => {
      currentPage.value = newPage
      loadQuestions(newPage, currentPageSize.value)
    }
    
    // 加载大量数据（尝试获取所有数据）
    const loadMassiveData = async () => {
      try {
        loading.value = true
        ElMessage.info('正在尝试加载所有数据...')
        
        // 尝试用大页面大小加载
        const [logistResult, videoResult] = await Promise.all([
          loadLogistQuestions(1, 1000),
          loadVideoQuestions(1, 1000)
        ])
        
        const allQuestions = [...logistResult.questions, ...videoResult.questions]
        
        if (allQuestions.length > 0) {
          questions.value = allQuestions
          totalQuestions.value = logistResult.total + videoResult.total
          currentPageSize.value = allQuestions.length
          currentPage.value = 1
          isUsingMockData.value = false
          
          ElMessage.success(`成功加载所有数据：${allQuestions.length} 个题目`)
        } else {
          ElMessage.warning('没有找到数据')
        }
      } catch (error) {
        console.error('加载大量数据失败:', error)
        ElMessage.error('加载失败，请尝试使用分页浏览')
      } finally {
        loading.value = false
      }
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadMockData()
      setTimeout(() => {
        loadQuestions()
      }, 100)
    })
    

    
    return {
      activeStage,
      selectedSkill,
      stageOptions,
      questions,
      showQuestionDialog,
      showPreviewDialog,
      showAIGenerateDialog,
      showFeishuDialog,
      showImportHelp,
      previewingQuestion,
      currentQuestionType,
      questionForm,
      filteredQuestions,
      allSkillTags,
      mockInterviews,
      loading,
      isUsingMockData,
      // 分页相关
      currentPage,
      currentPageSize,
      totalQuestions,
      allQuestionsCache,
      getStageTagType,
      getStageLabel,
      getCategoryLabel,
      getDialogTitle,
      getImageUrl,
      handleImageError,
      handleAddQuestion,
      handleImport,
      importFromClipboard,
      importFromCSV,
      downloadCSVExample,
      saveImportedQuestions,
      convertToExamsFormat,
      convertToSparkFormat,
      createSkillTag,
      uploadContentImage,
      uploadOptionImage,
      editQuestion,
      deleteQuestion,
      previewQuestion,
      saveQuestion,
      generateQuestions,
      generateQuestionsForInterview,
      connectFeishu,
      exportQuestions,
      loadQuestions,
      loadMockData,
      loadFilteredQuestions,
      handlePageSizeChange,
      handleCurrentPageChange
    }
  }
}
</script>

<style scoped>
.question-bank-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  color: #333;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  margin: 0;
}

/* 筛选区域样式 */
.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.filter-tabs {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  margin-right: 8px;
}

.filter-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.filter-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.filter-tag.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.filter-skill {
  display: flex;
  align-items: center;
}

/* 统计信息样式 */
.stats-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.stats-info {
  display: inline-flex;
  align-items: baseline;
  gap: 4px;
  font-size: 14px;
  color: #666;
  padding: 4px 12px;
  background: #f5f5f5;
  border-radius: 12px;
  border: 1px solid #e0e0e0;
}

.stats-count {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.stats-total {
  font-size: 12px;
  color: #999;
}

.stats-remote {
  font-size: 12px;
  color: #f56c6c;
  font-weight: 500;
}

.pagination-info {
  display: flex;
  align-items: center;
}

.pagination-info .el-pagination {
  --el-pagination-font-size: 13px;
  --el-pagination-button-width: 28px;
  --el-pagination-button-height: 28px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-section {
  display: flex;
  gap: 8px;
}

.questions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.question-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.question-card:hover {
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.question-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.question-content {
  color: #666;
  line-height: 1.5;
  margin-bottom: 16px;
}

.question-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.skill-tag {
  background: #f0f2f5;
  color: #333;
  border: none;
}

.question-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #666;
}

.preview-content {
  padding: 16px;
}

.preview-content h3 {
  margin-bottom: 16px;
  color: #303133;
}

.preview-short-answer {
  margin-top: 20px;
}

.preview-section {
  margin-bottom: 16px;
}

.preview-section h4 {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 600;
}

.preview-section p {
  margin: 0;
  color: #606266;
  line-height: 1.5;
}

.scoring-criteria {
  color: #606266;
  line-height: 1.5;
}

.positions-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.preview-content h3 {
  color: #333;
  margin-bottom: 16px;
}

.preview-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
}

.preview-meta {
  display: flex;
  align-items: center;
  gap: 16px;
}

.unit {
  margin-left: 8px;
  color: #666;
}

.upload-hint {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-name {
  font-size: 12px;
  color: #666;
}

.option-input {
  display: flex;
  align-items: center;
  gap: 12px;
}

.option-input .el-input {
  flex: 1;
}

.ai-generate-content {
  padding: 16px;
}

.ai-header {
  margin-bottom: 24px;
  text-align: center;
}

.ai-header h3 {
  color: #333;
  margin-bottom: 8px;
}

.ai-header p {
  color: #666;
}

.interview-list {
  margin-bottom: 32px;
}

.interview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 12px;
}

.interview-item:hover {
  background-color: #f5f7fa;
}

.interview-info h4 {
  color: #333;
  margin-bottom: 8px;
}

.interview-info p {
  color: #666;
  margin-bottom: 8px;
}

.interview-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.feishu-integration {
  border-top: 1px solid #e4e7ed;
  padding-top: 24px;
}

.feishu-integration h3 {
  color: #333;
  margin-bottom: 16px;
}

.feishu-config {
  display: flex;
  align-items: center;
  gap: 16px;
}

.feishu-hint {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.feishu-content {
  padding: 16px;
}

.feishu-status {
  margin-top: 16px;
}

/* 新增样式 */
.loading-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.question-image {
  margin: 12px 0;
  text-align: center;
}

.question-image img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.options-preview {
  margin: 12px 0;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 4px;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.option-label {
  font-weight: 600;
  margin-right: 8px;
  color: #333;
}

.option-content {
  color: #666;
}

.more-options {
  color: #999;
  font-size: 12px;
  font-style: italic;
}

.preview-image {
  margin: 16px 0;
  text-align: center;
}

.preview-image img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-options {
  margin: 16px 0;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 4px;
}

.preview-options h4 {
  margin-bottom: 12px;
  color: #333;
}

.preview-option-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  padding: 8px;
  background: white;
  border-radius: 4px;
}

.preview-option-item .option-label {
  font-weight: 600;
  margin-right: 8px;
  color: #333;
  min-width: 20px;
}

.preview-option-item .option-content {
  flex: 1;
  color: #666;
}

.option-image {
  margin-top: 8px;
}

.option-image img {
  max-width: 100px;
  max-height: 100px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.correct-answer {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.preview-answer {
  margin: 16px 0;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 4px;
}

.preview-answer h4 {
  margin-bottom: 8px;
  color: #333;
}

.preview-answer p {
  color: #666;
  font-weight: 500;
}

.data-status-alert {
  margin: 16px 0;
}

.data-status-alert .el-alert__content {
  line-height: 1.6;
}

.data-status-alert ol {
  margin: 8px 0;
  padding-left: 20px;
}

.data-status-alert li {
  margin: 4px 0;
}

/* 导入相关样式 */
.import-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.import-item span {
  font-size: 14px;
  color: #333;
}

.import-item small {
  font-size: 12px;
  color: #999;
}

/* 导入帮助对话框样式 */
.import-help-content {
  padding: 20px;
}

.help-section {
  margin-bottom: 32px;
}

.help-section h3 {
  color: #333;
  margin-bottom: 16px;
  font-size: 16px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.help-section p {
  line-height: 1.6;
  color: #666;
  margin-bottom: 12px;
}

.help-section ul {
  margin-left: 20px;
  line-height: 1.8;
}

.help-section li {
  margin-bottom: 8px;
  color: #666;
}

.help-example {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  margin: 16px 0;
}

.help-example pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #333;
  white-space: pre-wrap;
}

.help-tip {
  background: #e8f4fd;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  padding: 12px;
  margin: 12px 0;
  font-size: 14px;
  color: #0066cc;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

</style> 